package com.zxy.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zxy.dao.TravelGroupDao;
import com.zxy.entity.PageResult;
import com.zxy.pojo.TravelGroup;
import com.zxy.service.TravelGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    TravelGroupDao travelGroupDao;

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }

    @Override
    public void delete(Integer id) {
        List<Integer> travelItemIdsByTravelGroupId = travelGroupDao.getTravelItemIdsByTravelGroupId(id);
        if (travelItemIdsByTravelGroupId.size()>0) {
            throw new RuntimeException();
        }else {
            travelGroupDao.deleteToTravelGroup(id);
        }

    }

    @Override
    public void edit(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.edit(travelGroup);
        Integer travelGroupId = travelGroup.getId();

        // 先删除中间表的关联数据
        travelGroupDao.delete(travelGroupId);
        // 重新再增加关联数据
        setTravelGroupAndTravelItem(travelGroupId,travelItemIds);
    }

    @Override
    public List<Integer> getTravelItemIdsByTravelGroupId(Integer id) {
        return travelGroupDao.getTravelItemIdsByTravelGroupId(id);
    }

    @Override
    public TravelGroup getById(Integer id) {
        return travelGroupDao.getById(id);
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        // 使用分页插件PageHelper，设置当前页，每页最多显示的记录数
        PageHelper.startPage(currentPage,pageSize);
        Page page = travelGroupDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(TravelGroup travelGroup, Integer[] travelItemIds) {
        // 1.新增跟团游，向 t_travelgroup中添加数据，新增后返回新增的id
        travelGroupDao.add(travelGroup);
        // 2 新增跟团游和自由行中间表t_travelgroup_travelitem新增数据(新增几条，由travelItemIds决定)
        setTravelGroupAndTravelItem(travelGroup.getId(),travelItemIds);

    }

    private void setTravelGroupAndTravelItem(Integer travelGroupId, Integer[] travelItemIds) {
        if (travelItemIds != null && travelItemIds.length>0){
            for (Integer travelItemId : travelItemIds) {
                Map<String,Integer> map = new HashMap();
                map.put("travelGroup",travelGroupId);
                map.put("travelItem",travelItemId);
                travelGroupDao.setTravelGroupAndTravelItem(map);
            }
        }
    }
}
